package cn.nihao365.controller;

import cn.nihao365.model.Users;
import cn.nihao365.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @author zhu hui (zhuhui@nihao365.cn)
 * @version 1.0
 * @date 2021-10-24 23:56:44
 */
@Controller
public class TestController{
    private final UserService userService;

    @Autowired
    public TestController(UserService userService){
        this.userService = userService;
    }

    @RequestMapping("/test")
    public String index(Model model){
        model.addAttribute("message","这是一个测试页面");
        return "test/index";
    }

    @GetMapping("/test/user")
    public String user(Model model) {
        Users users = userService.getUserById(12);
        model.addAttribute("user", users);
        return "test/user";
    }

    @RequestMapping("/upload")
    public String singleFileUpload(@RequestParam(name = "file") MultipartFile file,HttpServletRequest request){
        if(null == file){
            request.setAttribute("msg","请选择上传的文件");
            return "test/result";
        }
        if(file.isEmpty()){
            request.setAttribute("msg","上传的文件内容不能为空！");
            return "test/result";
        }
        try{
            String filePath = request.getSession().getServletContext().getRealPath("/upload");
            File root = new File(filePath);
            if(!root.exists()){
                root.mkdir();
            }
            String fileName = file.getOriginalFilename();
            fileName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
            file.transferTo(new File(root,fileName));
            request.setAttribute("msg","文件上传成功");
        }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("msg","文件上传失败");
        }
        return "test/result";
    }

}
